package com.shop.cereshop.commons.utils;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class BusinessWeeksUtils {

    // 定义中文星期的顺序（用于排序和连续性判断）
    private static final List<String> WEEKDAYS_ORDER = Arrays.asList(
            "周一", "周二", "周三", "周四", "周五", "周六", "周日"
    );

    /**
     * 合并营业日期为紧凑格式（如 "周一、周三至周五"）
     * @param dayStrings 选择的星期几（如 ["周一", "周三", "周四", "周五"]）
     * @return 合并后的字符串
     */
    public static String mergeWeeks(List<String> dayStrings) {
        if (dayStrings == null || dayStrings.isEmpty()) {
            return "未营业";
        }

        // 去重并按星期顺序排序
        List<String> sortedDays = dayStrings.stream()
                .distinct()
                .sorted(Comparator.comparingInt(WEEKDAYS_ORDER::indexOf))
                .collect(Collectors.toList());

        StringBuilder result = new StringBuilder();
        List<List<String>> consecutiveGroups = new ArrayList<>();
        List<String> currentGroup = new ArrayList<>();
        currentGroup.add(sortedDays.get(0));

        // 将连续的日期分组
        for (int i = 1; i < sortedDays.size(); i++) {
            String current = sortedDays.get(i);
            String previous = sortedDays.get(i - 1);

            // 检查是否连续（通过星期顺序索引判断）
            if (WEEKDAYS_ORDER.indexOf(current) == WEEKDAYS_ORDER.indexOf(previous) + 1) {
                currentGroup.add(current);
            } else {
                consecutiveGroups.add(new ArrayList<>(currentGroup));
                currentGroup.clear();
                currentGroup.add(current);
            }
        }
        consecutiveGroups.add(currentGroup);

        // 处理每个连续分组
        for (int i = 0; i < consecutiveGroups.size(); i++) {
            if (i > 0) {
                result.append(",");
            }

            List<String> group = consecutiveGroups.get(i);
            if (group.size() >= 3) {
                // 3个及以上连续天数用"至"连接
                result.append(group.get(0)).append("至").append(group.get(group.size() - 1));
            } else {
                // 少于3个连续天数用逗号分隔
                for (int j = 0; j < group.size(); j++) {
                    if (j > 0) {
                        result.append(",");
                    }
                    result.append(group.get(j));
                }
            }
        }

        return result.toString();
    }
}
